﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NHibernate;
using DotNet.Common.NHibernateUtil;
using System.Threading;
using DotNet.Common.Command;
using ZLCMS.Commands.Sys.Commands.Shop;

namespace ZLCMS.Web.Tools
{
    public partial class UpdateStatus : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string key = "ebp9ZHBspMW8XUWzdNppzG6d3BlgmdS9";
            if (Request["key"] != key)
            {
                Response.Write("param error");
                return;
            }

            int taskId = 0;
            using(ISession session = SessionFactoryHelper.CreateSession())
            {
                taskId = session.CreateSQLQuery("select recid from sys_task_info where status=1").UniqueResult<int>();
                if (taskId > 0)
                {
                    Response.Write("已存在运行中的任务");
                    return;
                }
                taskId = Convert.ToInt32(session.CreateSQLQuery("INSERT into sys_task_info (start_date,status) VALUES(:date,1);select @@IDENTITY; ")
                    .SetParameter("date", DateTime.Now)
                    .UniqueResult());
            }

            Thread thread = new Thread(delegate()
            {
                int stepId = 0;

                //系统开始运行的时间
                var systemStartTime = new DateTime(2015, 7, 1);

                using (ISession session = SessionFactoryHelper.CreateSession())
                {
                    //生成交易数据
                    for (DateTime currentDate = systemStartTime; currentDate <= DateTime.Now.Date.AddDays(-1); currentDate = currentDate.AddDays(1))
                    {
                        string date = string.Format("{0:yyyyMMdd}", currentDate);
                        //检查当前日期是否已生成
                        int dateId = session.CreateSQLQuery("select recid from sys_task_step where step_key='GenerateProductTrade_" + date + "' and status=1").UniqueResult<int>();
                        if (dateId == 0)
                        {
                            GenerateProductTradeParameter generateProductTradeParameter = new GenerateProductTradeParameter()
                            {
                                Date = currentDate
                            };
                            stepId = CreateStep(session, taskId, "GenerateProductTrade_" + date, Newtonsoft.Json.JsonConvert.SerializeObject(generateProductTradeParameter));
                            ICommandResult<GenerateProductTradeResult> generateProductTradeResult = new GenerateProductTradeCommand().Execute(session, generateProductTradeParameter);
                            EndStep(session, stepId, Newtonsoft.Json.JsonConvert.SerializeObject(generateProductTradeResult), generateProductTradeResult.Error ? 0 : 1);
                        }
                    }

                    //生成产品日账单
                    for (DateTime currentDate = systemStartTime; currentDate <= DateTime.Now.Date.AddDays(-1); currentDate = currentDate.AddDays(1))
                    {
                        string date = string.Format("{0:yyyyMMdd}", currentDate);

                        //检查当日交易数据是否已生成（生成成功才能生成产品日账单）
                        //int tradeDateId = session.CreateSQLQuery("select recid from sys_task_step where step_key='GenerateProductTrade_" + date + "' and status=1").UniqueResult<int>();
                        //if (tradeDateId == 0) continue;

                        //检查当前日期是否已生成
                        int dateId = session.CreateSQLQuery("select recid from sys_task_step where step_key='GenerateProductDailyBill_" + date + "' and status=1").UniqueResult<int>();
                        if (dateId == 0)
                        {
                            GenerateProductDailyBillParameter generateProductDailyBillParameter = new GenerateProductDailyBillParameter()
                            {
                                Date = currentDate
                            };
                            stepId = CreateStep(session, taskId, "GenerateProductDailyBill_" + date, Newtonsoft.Json.JsonConvert.SerializeObject(generateProductDailyBillParameter));
                            ICommandResult<GenerateProductDailyBillResult> generateProductDailyBillResult = new GenerateProductDailyBillCommand().Execute(session, generateProductDailyBillParameter);
                            EndStep(session, stepId, Newtonsoft.Json.JsonConvert.SerializeObject(generateProductDailyBillResult), generateProductDailyBillResult.Error ? 0 : 1);
                        }
                    }

                    //生成日账单
                    for (DateTime currentDate = systemStartTime; currentDate <= DateTime.Now.Date.AddDays(-1); currentDate = currentDate.AddDays(1))
                    {
                        string date = string.Format("{0:yyyyMMdd}", currentDate);
                        //检查当前日期是否已生成
                        int dateId = session.CreateSQLQuery("select recid from sys_task_step where step_key='GenerateDailyBill_" + date + "' and status=1").UniqueResult<int>();
                        if (dateId == 0)
                        {
                            GenerateDailyBillParameter generateDailyBillParameter = new GenerateDailyBillParameter()
                            {
                                Date = currentDate
                            };
                            stepId = CreateStep(session, taskId, "GenerateDailyBill_" + date, Newtonsoft.Json.JsonConvert.SerializeObject(generateDailyBillParameter));
                            ICommandResult<GenerateDailyBillResult> generateDailyBillResult = new GenerateDailyBillCommand().Execute(session, generateDailyBillParameter);
                            EndStep(session, stepId, Newtonsoft.Json.JsonConvert.SerializeObject(generateDailyBillResult), generateDailyBillResult.Error ? 0 : 1);
                        }
                    }

                    //2015/7/1 - 2016/1/17 日统一结算
                    {
                        DateTime currentDate = new DateTime(2015, 7, 1);
                        DateTime endDate = new DateTime(2016, 1, 17);
                        string no = string.Format("{0:yyyyMMdd}x{1:yyyyMMdd}", currentDate, endDate);

                        //检查当前是否已生成
                        int dateId = session.CreateSQLQuery("select recid from sys_task_step where step_key='GenerateWeeklyBill_" + no + "' and status=1").UniqueResult<int>();
                        if (dateId == 0)
                        {
                            GenerateWeeklyBillParameter generateWeeklyBillParameter = new GenerateWeeklyBillParameter()
                            {
                                Start = currentDate,
                                End = endDate
                            };
                            stepId = CreateStep(session, taskId, "GenerateWeeklyBill_" + no, Newtonsoft.Json.JsonConvert.SerializeObject(generateWeeklyBillParameter));
                            ICommandResult<GenerateWeeklyBillResult> generateWeeklyBillResult = new GenerateWeeklyBillCommand().Execute(session, generateWeeklyBillParameter);
                            EndStep(session, stepId, Newtonsoft.Json.JsonConvert.SerializeObject(generateWeeklyBillResult), generateWeeklyBillResult.Error ? 0 : 1);
                        }
                    }


                    //生成周账单(2016/1/18日起按周结算)
                    for (DateTime currentDate = new DateTime(2016, 1, 18); true; )
                    {
                        int weekendCnt = 6 - Convert.ToInt32(currentDate.DayOfWeek);
                        DateTime endDate = currentDate.AddDays(weekendCnt);

                        if (endDate > DateTime.Now.Date.AddDays(-1))
                        {
                            break;
                        }
                        string no = string.Format("{0:yyyyMMdd}x{1:yyyyMMdd}", currentDate, endDate);

                        //检查当前是否已生成
                        int dateId = session.CreateSQLQuery("select recid from sys_task_step where step_key='GenerateWeeklyBill_" + no + "' and status=1").UniqueResult<int>();
                        if (dateId == 0)
                        {
                            GenerateWeeklyBillParameter generateWeeklyBillParameter = new GenerateWeeklyBillParameter()
                            {
                                Start = currentDate,
                                End = endDate
                            };
                            stepId = CreateStep(session, taskId, "GenerateWeeklyBill_" + no, Newtonsoft.Json.JsonConvert.SerializeObject(generateWeeklyBillParameter));
                            ICommandResult<GenerateWeeklyBillResult> generateWeeklyBillResult = new GenerateWeeklyBillCommand().Execute(session, generateWeeklyBillParameter);
                            EndStep(session, stepId, Newtonsoft.Json.JsonConvert.SerializeObject(generateWeeklyBillResult), generateWeeklyBillResult.Error ? 0 : 1);
                        }
                        currentDate = endDate.AddDays(1);
                    }



                    //下载微信对账单
                    for (DateTime currentDate = systemStartTime; currentDate < DateTime.Now.Date.AddDays(-1); currentDate = currentDate.AddDays(1))
                    {
                        string date = string.Format("{0:yyyyMMdd}", currentDate);
                        //检查当前日期是否已下载
                        int dateId = session.CreateSQLQuery("select recid from sys_task_step where step_key='DownloadWXPayBill_" + date + "' and status=1").UniqueResult<int>();
                        if (dateId == 0)
                        {
                            ZLCMS.Commands.Sys.Commands.Order.DownloadWXPayBillParameter downloadWXPayBillParameter = new ZLCMS.Commands.Sys.Commands.Order.DownloadWXPayBillParameter()
                            {
                                Date = date,
                                BillType = "ALL"
                            };
                            stepId = CreateStep(session, taskId, "DownloadWXPayBill_" + downloadWXPayBillParameter.Date, Newtonsoft.Json.JsonConvert.SerializeObject(downloadWXPayBillParameter));
                            ICommandResult<ZLCMS.Commands.Sys.Commands.Order.DownloadWXPayBillResult> downloadWXPayBillResult = new ZLCMS.Commands.Sys.Commands.Order.DownloadWXPayBillCommand().Execute(session, downloadWXPayBillParameter);
                            EndStep(session, stepId, Newtonsoft.Json.JsonConvert.SerializeObject(downloadWXPayBillResult), downloadWXPayBillResult.Error ? 0 : 1);
                        }
                    }
                    ////自动确认订单
                    //stepId = CreateStep(session, taskId, "ConfirmPaidOrder", "{}");
                    //ICommandResult<ZLCMS.Commands.Sys.Commands.Order.ConfirmPaidOrderResult> confirmPaidOrderResult = new ZLCMS.Commands.Sys.Commands.Order.ConfirmPaidOrderCommand().Execute(session, new ZLCMS.Commands.Sys.Commands.Order.ConfirmPaidOrderParameter() { });
                    //EndStep(session, stepId, Newtonsoft.Json.JsonConvert.SerializeObject(confirmPaidOrderResult), confirmPaidOrderResult.Error ? 0 : 1);

                    //取消超时订单
                    //stepId = CreateStep(session, taskId, "CancelTimeoutOrders", "{}");
                    //ICommandResult<ZLCMS.Commands.Sys.Commands.Order.CancelTimeoutOrdersResult> cancelTimeoutOrdersResult = new ZLCMS.Commands.Sys.Commands.Order.CancelTimeoutOrdersCommand().Execute(session, new ZLCMS.Commands.Sys.Commands.Order.CancelTimeoutOrdersParameter() { });
                    //EndStep(session, stepId, Newtonsoft.Json.JsonConvert.SerializeObject(cancelTimeoutOrdersResult), cancelTimeoutOrdersResult.Error ? 0 : 1);

                    //自动签收到期包裹
                    stepId = CreateStep(session, taskId, "FinishPackage", "{}");
                    ICommandResult<ZLCMS.Commands.Sys.Commands.Order.FinishPackageResult> finishPackageResult = new ZLCMS.Commands.Sys.Commands.Order.FinishPackageCommand().Execute(session, new ZLCMS.Commands.Sys.Commands.Order.FinishPackageParameter() { });
                    EndStep(session, stepId, Newtonsoft.Json.JsonConvert.SerializeObject(finishPackageResult), finishPackageResult.Error ? 0 : 1);

                    //DateTime endDate = DateTime.Now.AddDays(1).Date;
                    //DateTime startDate = endDate.AddMonths(-3);

                    //生成销量统计
                    //new ZLCMS.Commands.Sys.Commands.Product.CreateSalesSummaryCommand().Execute(session, new ZLCMS.Commands.Sys.Commands.Product.CreateSalesSummaryParameter() { StartDate = startDate, EndDate = endDate });

                    ////生成提成数据
                    //new ZLCMS.Commands.Sys.Commands.Agent.CreateBonusSummaryCommand().Execute(new ZLCMS.Commands.Sys.Commands.Agent.CreateBonusSummaryParameter() { StartDate = startDate, EndDate = endDate });

                    ////生成代理商销量数据
                    //new ZLCMS.Commands.Sys.Commands.Agent.CreateSalesSummaryCommand().Execute(new ZLCMS.Commands.Sys.Commands.Agent.CreateSalesSummaryParameter() { StartDate = startDate, EndDate = endDate });


                    //结束当前任务
                    session.CreateSQLQuery("update sys_task_info set end_date=:d,status=9 where recid=:tid")
                        .SetParameter("d", DateTime.Now)
                        .SetParameter("tid", taskId)
                        .ExecuteUpdate();
                    session.Flush();
                }
                });
            thread.Start();
            
            Response.Write("success");
        }

        protected int CreateStep(ISession session, int taskId, string key, string paramJson)
        {
            return Convert.ToInt32(session.CreateSQLQuery("INSERT into sys_task_step (task_id,start_date,step_key,step_param,status) VALUES(:tid,:date,:key,:param,0);select @@IDENTITY; ")
                           .SetParameter("date", DateTime.Now)
                           .SetParameter("tid", taskId)
                           .SetParameter("key", key)
                           .SetParameter("param", paramJson)
                           .UniqueResult());
        }

        protected void EndStep(ISession session, int stepId, string resultJson,int stat)
        {
            session.CreateSQLQuery("update sys_task_step set end_date=:d,step_result=:r,status=:s where recid=:sid")
                .SetParameter("d", DateTime.Now)
                .SetParameter("r", resultJson)
                .SetParameter("sid", stepId)
                .SetParameter("s", stat)
                .ExecuteUpdate();
        }
    }
}